<template>
  <div class="ranking-page">
    <NavHeader
      title="分红排行榜"
      @back="onClickLeft"
    />
    
    <!-- 顶部奖杯区域 -->
    <div class="trophy-section">
      <div class="trophy-background"></div>
      <div class="trophy-content">
        <div class="trophy-title">
          {{ currentYear }}年第{{ currentWeek }}周排行榜
          <van-icon name="question-o" class="help-icon" @click="showRules = true" />
        </div>
        <div class="trophy-subtitle">每日00:00更新</div>
        
        <!-- 周数选择器 -->
        <div class="week-selector">
          <div class="week-selector-inner">
            <div 
              v-for="week in availableWeeks" 
              :key="week" 
              :class="['week-item', week === currentWeek ? 'active' : '']"
              @click="changeWeek(week)"
            >
              第{{ week }}周
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 前三名展示区 -->
    <div class="top-three-section">
      <!-- 第二名 -->
      <div class="top-player second-place" v-if="rankingList.length > 1">
        <div class="crown crown-silver">2</div>
        <div class="player-avatar">
          <div class="avatar-text">{{ getAvatarText(rankingList[1].address) }}</div>
        </div>
        <div class="player-name">{{ rankingList[1].nickname }}</div>
        <div class="player-reward" :class="{'current-week': isCurrentWeek}">{{ formatNumber(rankingList[1].reward) }} {{ rankingList[1].name }}</div>
      </div>
      
      <!-- 第一名 -->
      <div class="top-player first-place" v-if="rankingList.length > 0">
        <div class="crown crown-gold">1</div>
        <div class="player-avatar">
          <div class="avatar-text">{{ getAvatarText(rankingList[0].address) }}</div>
        </div>
        <div class="player-name">{{ rankingList[0].nickname }}</div>
        <div class="player-reward" :class="{'current-week': isCurrentWeek}">{{ formatNumber(rankingList[0].reward) }} {{ rankingList[0].name }}</div>
      </div>
      
      <!-- 第三名 -->
      <div class="top-player third-place" v-if="rankingList.length > 2">
        <div class="crown crown-bronze">3</div>
        <div class="player-avatar">
          <div class="avatar-text">{{ getAvatarText(rankingList[2].address) }}</div>
        </div>
        <div class="player-name">{{ rankingList[2].nickname }}</div>
        <div class="player-reward" :class="{'current-week': isCurrentWeek}">{{ formatNumber(rankingList[2].reward) }} {{ rankingList[2].name }}</div>
      </div>
    </div>
    
    <!-- 排名列表 -->
    <div class="ranking-container">
      <div class="ranking-list">
        <div v-if="loading" class="loading-container">
          <van-loading type="spinner" color="var(--primary-color)" />
        </div>
        <template v-else>
          <!-- 从第4名开始显示，最多显示到第100名 -->
          <div v-for="(item, index) in rankingList.slice(3, 100)" :key="index + 3" class="ranking-item">
            <div class="rank-column">
              <div class="rank-badge">{{ index + 4 }}</div>
            </div>
            <div class="user-column">
              <div class="user-info">
                <!-- <div class="user-avatar-small">{{ getAvatarText(item.address) }}</div> -->
                <div class="user-details">
                  <div class="user-name">{{ item.nickname }}</div>
                  <div class="user-address">{{ formatAddress(item.address) }}</div>
                </div>
              </div>
            </div>
            <div class="reward-column" :class="{'current-week': isCurrentWeek}">
              {{ formatNumber(item.reward) }} U
            </div>
          </div>
          <div v-if="rankingList.length === 0" class="empty-data">
            暂无排名数据
          </div>
        </template>
      </div>
    </div>
    
    <!-- 底部悬浮我的排名 -->
    <div class="my-ranking-bar">
      <div class="my-ranking-content">
        <!-- <div class="my-avatar">
          <div class="my-avatar-text">{{ getAvatarText(myRanking.address) }}</div>
        </div> -->
        <div class="my-info">
          <div class="my-name">{{ myRanking.nickname || '我' }}</div>
          <div class="my-rank-text">
            <template v-if="myRanking.rank <= 100 && myRanking.rank > 0">
              当前排名: <span class="my-rank-number">{{ myRanking.rank }}</span>
            </template>
            <template v-else>
              当前排名: <span class="my-rank-number">百名开外</span>
            </template>
          </div>
        </div>
        <div class="my-reward" :class="{'current-week': isCurrentWeek}">
          {{ formatNumber(myRanking.reward) }} {{ myRanking.name }}
        </div>
      </div>
    </div>
    
    <!-- 排名规则弹窗 -->
    <van-popup
      v-model:show="showRules"
      round
      position="bottom"
      :style="{ height: '70%' }"
      class="rules-popup"
    >
      <div class="rules-container">
        <div class="rules-header">
          <div class="rules-title">排名规则</div>
          <van-icon name="cross" class="close-icon" @click="showRules = false" />
        </div>
        
        <div class="rules-content">
          <div class="rules-card">
            <h3 class="rules-subtitle">排名规则</h3>
            <div class="rules-text">
              <p>1. 排名根据用户参与分红池的业绩总量进行排序，业绩越高排名越靠前。</p>
              <p>2. 本期排名统计当前周期内的业绩数据，每周一00:00更新。</p>
              <p>3. 上期排名展示上一周期的最终排名及奖励情况。</p>
              <p>4. 排名奖励将在每周一自动发放到用户账户中。</p>
            </div>
          </div>
          
          <div class="rules-card">
            <h3 class="rules-subtitle">奖励说明</h3>
            <div class="rules-text">
              <p>1. 排名奖励根据用户排名位置和业绩总量计算。</p>
              <p>2. 排名奖励计算公式：</p>
              <div class="formula">
                <p>- 第1名：基础奖励 × 3.0</p>
                <p>- 第2名：基础奖励 × 2.0</p>
                <p>- 第3名：基础奖励 × 1.5</p>
                <p>- 第4-10名：基础奖励 × 1.2</p>
                <p>- 第11-50名：基础奖励 × 1.0</p>
              </div>
              <p>3. 基础奖励根据当期分红池总量的5%按比例分配。</p>
              <p>4. 用户需要持续参与分红池才能获得排名奖励。</p>
            </div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import NavHeader from '@/components/NavHeader.vue'
import { poolRank } from '@/api/dividend'
import {formatNumber} from '@/utils/utils'

const router = useRouter()
const loading = ref(true)
const showRules = ref(false)

// 年份和周数相关
const currentDate = new Date()
const systemYear = ref(currentDate.getFullYear())
const systemWeek = ref(getCurrentWeek())
const currentYear = ref(systemYear.value)
const currentWeek = ref(systemWeek.value)
const availableWeeks = computed(() => {
  const weeks = []
  for (let i = 0; i <= 4; i++) {
    const week = systemWeek.value - i
    if (week > 0) weeks.push(week)
  }
  return weeks
})

// 判断是否为当前周
const isCurrentWeek = computed(() => {
  return currentWeek.value === systemWeek.value && currentYear.value === systemYear.value
})

// 排行榜数据
const weeklyRankingData = ref({})
const rankingList = computed(() => {
  const key = `${currentYear.value}-${currentWeek.value}`
  const data = weeklyRankingData.value[key] || []
  return data.map(item => ({
    id: item.id,
    address: item.address,
    nickname: item.userName,
    reward: item.totalAmt
  }))
})

// 我的排名数据
const myRanking = ref({
  rank: 0,
  nickname: '我的账户',
  address: '0x' + Math.random().toString(16).substring(2, 42),
  reward: '0.00',
  icon: 'U'
})

onMounted(async () => {
  await fetchRankingData()
})

// 获取当前是第几周
function getCurrentWeek() {
  const now = new Date()
  const start = new Date(now.getFullYear(), 0, 1)
  const diff = now - start + (start.getTimezoneOffset() - now.getTimezoneOffset()) * 60 * 1000
  const oneWeek = 604800000
  return Math.floor(diff / oneWeek) + 1
}

// 切换周数
function changeWeek(week) {
  currentWeek.value = week
  const key = `${currentYear.value}-${week}`
  if (!weeklyRankingData.value[key]) {
    loading.value = true
    fetchRankingData()
  }
}

// 获取头像文本
function getAvatarText(address) {
  if (!address) return '???'
  return address.substring(address.length - 6)
}

// 格式化地址
const formatAddress = (address) => {
  if (!address) return ''
  return address.substring(0, 6) + '...' + address.substring(address.length - 4)
}

const fetchRankingData = async () => {
  loading.value = true
  try {
    const response = await poolRank({
      weeks: currentWeek.value,
      year: currentYear.value
    })
    if(response && response.code === 0) {
      const key = `${currentYear.value}-${currentWeek.value}`
      weeklyRankingData.value[key] = response.data.rank || []
      if(response.data.userRank) {
        myRanking.value = {
          rank: response.data.userRank.sort,
          nickname: response.data.userRank.userName,
          address: response.data.userRank.address,
          reward: response.data.userRank.totalAmt,
          icon: response.data.userRank.name,
        }
      }
    }
  } catch (error) {
    console.error('获取排行榜数据失败', error)
  } finally {
    loading.value = false
  }
}

const onClickLeft = () => {
  router.back()
}
</script>

<style scoped>
.ranking-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 80px; /* 为底部悬浮栏留出空间 */
  max-width: 800px;
  margin: 0 auto;
}

/* 奖杯区域样式 */
.trophy-section {
  position: relative;
  height: 160px;
  margin-top: 44px;
  overflow: hidden;
  border-radius: 0 0 16px 16px;
}

.trophy-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #1989fa, #0960c5);
  z-index: 1;
}

.trophy-background::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><path d="M50 25L60 40L75 45L65 60L70 75L50 65L30 75L35 60L25 45L40 40Z" fill="rgba(255,255,255,0.1)"/></svg>');
  background-size: 100px;
  opacity: 0.3;
  z-index: -1;
}

.trophy-content {
  position: relative;
  z-index: 2;
  padding: 20px;
  text-align: center;
  color: white;
}

.trophy-title {
  font-size: 24px;
  font-weight: 700;
  margin-bottom: 8px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
}

.help-icon {
  margin-left: 8px;
  font-size: 18px;
  opacity: 0.8;
  cursor: pointer;
}

.trophy-subtitle {
  font-size: 14px;
  opacity: 0.8;
  margin-bottom: 16px;
}

/* 周数选择器 */
.week-selector {
  margin-top: 16px;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  padding-bottom: 8px;
}

.week-selector-inner {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.week-item {
  padding: 6px 12px;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.week-item.active {
  background-color: white;
  color: var(--primary-color);
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

/* 前三名展示区域 */
.top-three-section {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  padding: 0 20px;
  margin-top: -30px;
  margin-bottom: 30px;
  position: relative;
  z-index: 10;
  gap: 15px; /* 增加间距 */
}

.top-player {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  transition: transform 0.3s ease;
}

.top-player:hover {
  transform: translateY(-5px);
}

.first-place {
  z-index: 3;
  margin: 0 5px; /* 调整间距 */
}

.second-place, .third-place {
  z-index: 2;
}

.crown {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 700;
  font-size: 18px;
  position: absolute;
  top: -18px;
  left: 50%;
  transform: translateX(-50%);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  border: 2px solid white;
}

.crown-gold {
  background: linear-gradient(135deg, #ffd700, #ff9500);
}

.crown-silver {
  background: linear-gradient(135deg, #e0e0e0, #a0a0a0);
}

.crown-bronze {
  background: linear-gradient(135deg, #cd7f32, #8b4513);
}

.player-avatar {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  overflow: hidden;
  border: 3px solid white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.first-place .player-avatar {
  width: 90px;
  height: 90px;
  border: 4px solid #ffd700;
  box-shadow: 0 6px 16px rgba(255, 215, 0, 0.3);
}

.avatar-text {
  font-size: 16px;
  font-weight: 700;
  color: #333;
  text-transform: uppercase;
}

.first-place .avatar-text {
  font-size: 20px;
}

.player-name {
  margin-top: 8px;
  font-size: 14px;
  font-weight: 600;
  color: #333;
  max-width: 80px;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.first-place .player-name {
  font-size: 16px;
  max-width: 100px;
}

.player-reward {
  margin-top: 4px;
  font-size: 14px;
  font-weight: 700;
  color: #999;
  background-color: rgba(153, 153, 153, 0.1);
  padding: 4px 10px;
  border-radius: 20px;
}

.player-reward.current-week {
  color: #ff4d4f;
  background-color: rgba(255, 77, 79, 0.1);
}

.first-place .player-reward {
  font-size: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.first-place .player-reward.current-week {
  background: linear-gradient(135deg, rgba(255, 77, 79, 0.2), rgba(255, 77, 79, 0.1));
  box-shadow: 0 2px 8px rgba(255, 77, 79, 0.2);
}

/* 排名列表样式 */
.ranking-container {
  padding: 0 16px;
}

.ranking-list {
  padding: 0;
  background-color: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.ranking-item {
  display: flex;
  padding: 16px;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
  transition: all 0.3s ease;
  position: relative;
}

.ranking-item::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: 0;
  width: 0;
  height: 2px;
  background: linear-gradient(90deg, var(--primary-color), transparent);
  transition: width 0.3s ease;
}

.ranking-item:hover::after {
  width: 100%;
}

.ranking-item:hover {
  background-color: #f9f9f9;
}

.ranking-item:last-child {
  border-bottom: none;
}

.rank-column {
  width: 60px;
  text-align: center;
  margin-right: 10px;
}

.user-column {
  flex: 1;
  min-width: 0;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar-small {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  font-size: 12px;
  font-weight: 700;
  color: #333;
  text-transform: uppercase;
  flex-shrink: 0;
}

.user-details {
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-width: 0;
}

.user-address {
  font-size: 12px;
  color: #999;
  margin-top: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.rank-badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #f0f0f0;
  color: #666;
  font-size: 16px;
  font-weight: 600;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.ranking-item:hover .rank-badge {
  transform: scale(1.1);
}

.user-name {
  font-size: 15px;
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 140px;
  color: #333;
}

.loading-container {
  display: flex;
  justify-content: center;
  padding: 60px 0;
}

.empty-data {
  text-align: center;
  padding: 60px 0;
  color: #999;
  font-size: 16px;
}

.reward-column {
  width: 120px; /* 增加宽度 */
  text-align: right;
  font-size: 16px;
  font-weight: 600;
  padding: 8px 16px;
  border-radius: 20px;
  color: #999;
  background-color: rgba(153, 153, 153, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  flex-shrink: 0;
}

.reward-column.current-week {
  color: #ff4d4f;
  background-color: rgba(255, 77, 79, 0.1);
}

.ranking-item:hover .reward-column {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* 底部悬浮我的排名 */
.my-ranking-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 100;
  padding: 12px 16px;
  display: flex;
  justify-content: center;
}

.my-ranking-content {
  display: flex;
  align-items: center;
  width: 100%;
  max-width: 800px;
  background-color: #f9f9f9;
  border-radius: 12px;
  padding: 10px 16px;
}

.my-avatar {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  border: 2px solid white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.my-avatar-text {
  font-size: 14px;
  font-weight: 700;
  color: #333;
  text-transform: uppercase;
}

.my-info {
  flex: 1;
  min-width: 0;
}

.my-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.my-rank-text {
  font-size: 14px;
  color: #666;
  margin-top: 2px;
}

.my-rank-number {
  font-weight: 700;
  color: var(--primary-color);
}

.my-reward {
  width: 120px;
  text-align: right;
  font-size: 16px;
  font-weight: 600;
  padding: 8px 16px;
  border-radius: 20px;
  color: #999;
  background-color: rgba(153, 153, 153, 0.1);
}

.my-reward.current-week {
  color: #ff4d4f;
  background-color: rgba(255, 77, 79, 0.1);
}

/* 规则弹窗样式 */
.rules-popup {
  border-radius: 16px 16px 0 0;
}

.rules-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}

.rules-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.rules-title {
  font-size: 20px;
  font-weight: 700;
  color: #333;
}

.close-icon {
  font-size: 20px;
  color: #999;
  cursor: pointer;
}

.rules-card {
  background-color: #fff;
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border-left: 4px solid var(--primary-color);
}

.rules-subtitle {
  font-size: 18px;
  font-weight: 600;
  color: var(--primary-color);
  margin: 0 0 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #eee;
}

.rules-text p {
  margin: 12px 0;
  font-size: 15px;
  line-height: 1.6;
  color: #333;
}

.formula {
  background-color: #f5f7fa;
  border-radius: 12px;
  padding: 16px;
  margin: 16px 0;
  box-shadow: inset 0 2px 6px rgba(0, 0, 0, 0.05);
}

.formula p {
  margin: 8px 0;
  font-size: 14px;
  color: #555;
  font-weight: 500;
}
</style>